<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button style="float: right;" type="primary" @click="addEmployee">添加用户</el-button>
      </div>
      <template>
        <el-table
          :data="userList"
          border
          style="width: 100%"
        >
          <el-table-column
            prop="username"
            label="用户名"
            width="180"
          >
            <template v-slot="obj">
              <img class="avatar" :src="obj.row.image" alt="">
            </template>
          </el-table-column>
          <el-table-column
            prop="username"
            label="用户名"
            width="180"
          />
          <el-table-column
            prop="email"
            label="邮箱"
            style="width:33%"
          />
          <el-table-column
            label="操作"
          >
            <template v-slot="obj">
              <el-button type="primary" @click="editEmployeeRole(obj.row.id)">设置角色</el-button>
              <el-button @click="editEmployee(obj.row.id)">编辑</el-button>
              <el-button type="danger" @click="delEmployee(obj.row.id)">删除</el-button></template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 分页组件 -->
      <div class="block">
        <el-pagination
          layout="prev, pager, next"
          :page-size="pageConfig._limit"
          :total="total"
          :pager-count="5"
          @current-change="pageChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑弹出框 -->
    <el-dialog
      :visible="isShowRegister"
      :title="formData.id?'编辑用户':'添加用户'"
      @close="cancelFn"
    >
      <el-form ref="addUser" :model="formData" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="formData.email" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelFn">取 消</el-button>
        <el-button type="primary" @click="btnFn">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 角色弹出框 -->
    <template>
      <el-dialog
        :visible="isShowRole"
        title="设置角色"
        @close="cancelRoleFn"
      >
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            v-for="role in roleList"
            :key="role.id"
            :label="role.id"
          >
            {{ role.title }}
          </el-checkbox>
        </el-checkbox-group>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelRoleFn">取 消</el-button>
          <el-button type="primary" @click="btnRoleFn">提 交</el-button>
        </div>
      </el-dialog>
    </template>
  </div>
</template>

<script>
import { getUserList, getUserCount, registerUser, delUser, getUserId, editUserId } from '@/api/employess'
import { getRoleList } from '@/api/role'
// import { getUserDetail } from '@/api/user'
export default {
  data() {
    return {
      roleList: [], // 所有角色列表
      checkList: [], // 选中的列表
      isShowRole: false,
      isShowRegister: false,
      formData: {
        username: '',
        email: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        email: [{ required: true, message: '电子邮箱不能为空', trigger: 'blur' },
          { pattern: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/, message: '请输入正确邮箱号', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' },
          { max: 12, min: 4, message: '密码在4-12位之间', trigger: 'blur' }]
      },
      pageConfig: {
        _limit: 5,
        _start: 0
      },
      total: 0,
      userList: [] // 保存用户列表数据
    }
  },
  created() {
    // 获取用户列表
    this.getUserList()
    // 获取用户数量
    this.getUserCount()
  },
  methods: {
    // 点击提交
    async  btnRoleFn() {
      this.formData.roles = this.checkList
      // 发送请求
      await editUserId(this.formData)
      // 提醒用户
      this.$message.success('分配成功')
      // 更新页面
      this.getUserList()
      // 关闭弹框
      this.isShowRole = false
    },
    // 点击取消
    cancelRoleFn() {
      this.roleList = []
      this.checkList = []
      this.isShowRole = false
    },
    // 点击设置角色按钮
    async editEmployeeRole(id) {
      // 发送请求
      const res = await getRoleList()
      // 员工管理特定编辑接口
      const resUser = await getUserId(id)
      this.roleList = res.data
      this.formData = resUser.data
      // 拿到的是一个数组对象
      const arrCheckList = resUser.data.roles
      // 遍历数组对象，拿到每一项的id添加到checkList
      arrCheckList.forEach(obj => {
        this.checkList.push(obj.id)
      })
      // 弹出框
      this.isShowRole = true
    },
    // // 点击确认按钮
    async btnFn() {
      try {
      // 校验表单
        await this.$refs.addUser.validate()
        // 发送请求
        if (this.formData.id) {
          // 编辑用户
          await editUserId(this.formData)
        } else {
          // 添加用户
          await registerUser(this.formData)
        }
        // 提示用户
        this.$message.success('操作成功')
        // 关闭弹窗
        this.isShowRegister = false
        // 更新页面
        this.getUserList()
      } catch (error) {
        console.log(error)
      }
    },
    // 点击取消按钮
    cancelFn() {
      // 清理校验
      this.$refs.addUser.resetFields()
      // 清理数据
      this.formData = {
        username: '',
        email: '',
        password: ''
      }
      // 关闭弹窗
      this.isShowRegister = false
    },
    // 点击页码更新
    pageChange(newPage) {
      this.pageConfig._start = (newPage - 1) * this.pageConfig._limit
      this.getUserList()
    },
    // 获取用户列表
    async getUserList() {
      // 发送请求
      const res = await getUserList({ ...this.pageConfig })

      // 保存数据
      this.userList = res.data
      console.log(this.userList)
    },
    // 获取用户数量
    async getUserCount() {
      const res = await getUserCount()
      // console.log(res)
      this.total = res.data
    },
    // 添加用户
    addEmployee() {
      // 弹出弹框
      this.isShowRegister = true
    },
    // 编辑
    async editEmployee(id) {
      // 数据回显
      // 发送请求（ 获取指定用户）
      const res = await getUserId(id)
      console.log(res)
      this.formData = res.data
      this.isShowRegister = true
    },
    // 删除
    async delEmployee(id) {
      // 二次确认
      await this.$confirm('是否确认删除')
      // 发送请求
      await delUser(id)
      // 提示用户
      this.$message.success('删除成功')
      // 更新页面
      this.getUserList()
    }
  }
}
</script>

<style>
.el-card{
  margin: 20px;
}
.block{
   margin-top: 30px;
 text-align: center;
}
.avatar{
  width: 100%;
  height: 88px;
  object-fit: cover;
}

</style>
